package com.crayfish.quduo.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

import com.crayfish.quduo.App;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by crayfish on 2016/12/2.
 */
public abstract class BaseActivity extends AppCompatActivity{

    private ProgressDialog progressDialog;
    protected Activity mActivity;
    private Unbinder unbinder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        unbinder = ButterKnife.bind(this);
        mActivity = this;
        App.getInstance().addActivity(this);
        initEventAndData();
    }

    @Override
    protected void onDestroy() {
        unbinder.unbind();
        App.getInstance().removeActivity(this);
        if (progressDialog != null) {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            progressDialog = null;
        }
        super.onDestroy();
    }

    protected abstract int getLayoutId();
    protected abstract void initEventAndData();

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                onHomeBackBtnClick();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void showProgress(String msg){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(BaseActivity.this);
        }
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setMessage(msg);
        progressDialog.show();
    }

    public void showProgress(int res){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(BaseActivity.this);
        }
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setMessage(getResources().getString(res));
        progressDialog.show();
    }

    public void hideProgress(){
        if(progressDialog!=null&&progressDialog.isShowing()){
            progressDialog.dismiss();
        }
    }

    public void startMyActivity(Class clazz) {
        startActivity(new Intent(mActivity, clazz));
    }

    protected void onHomeBackBtnClick(){
        finish();
    }
}
